package xuan.mall.system.infrastructure.security.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.KeyUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.AlgorithmUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import xuan.mall.system.domain.entity.MallUserDetails;
import xuan.mall.system.infrastructure.security.config.JWTConfig;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author: rongxuanzhou
 * @create: 2025/6/1
 * @Description:
 */
public class MallJWTUtil {

    private static final JWTSigner signer = JWTSignerUtil.createSigner(
            JWTConfig.signature,
            KeyUtil.generateKeyPair(AlgorithmUtil.getAlgorithm(JWTConfig.signature))
    );

    public static String createToken(MallUserDetails mallUserDetails) {
        Map<String, Object> userMap = BeanUtil.beanToMap(mallUserDetails);
        return JWT.create()
                .addPayloads(userMap)
                .setExpiresAt(DateUtil.offsetMillisecond(DateUtil.date(), JWTConfig.expiration))
                .setKey(JWTConfig.secret.getBytes(StandardCharsets.UTF_8))
                .setSigner(signer)
                .sign();
    }

    public static MallUserDetails parseToken(String token) {
        if (JWTUtil.verify(token, signer)) {
            MallUserDetails jwt = parseToken(token);
        }
        return null;
    }
}
